package com.linwt.exceptions;

import java.net.BindException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linwt.util.Result;

@ControllerAdvice
public class GlobalExcepionHander {
	
	/**
	 * 全局一般异常
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Result exceptionHandler(Exception e) {
		
		
		Result result = new Result();
		result.setCode(300);
		result.setMsg("There was an unexpected error");
	
		return result;
	}

	
	/**
	 * 校验异常,返回json
	 * @return
	 */
	@ExceptionHandler(value= javax.validation.ConstraintViolationException.class)
	@ResponseBody
	public Result validationExceptionHandler(javax.validation.ConstraintViolationException e) {
		
	
		Result result = new Result();
		result.setCode(300);
		String msgStr = (String)  e.getMessage().subSequence( e.getMessage().lastIndexOf(".")+1, e.getMessage().length());
		String[] msgArr = msgStr.split(":");
		Map<String,Object> msgMap = new HashMap<String,Object>();	
		msgMap.put(msgArr[0],msgArr[1].trim() );
		
		result.setData(msgMap);
		result.setMsg("error");
		
		return result;
	}

	
}
